<?php

namespace app\user\controllers;

use mini\{Session, Validator};

class Password
{
    /**
     * 重置密码
     */
    public function reset()
    {
        if (REQUEST_TYPE !== 'post') {
            return json('请求方法不正确', 'error');
        }

        // 获取表单数据
        $data = [
            'oldPassword'  => post('oldPassword'),
            'newPassword1' => post('newPassword1'),
            'newPassword2' => post('newPassword2'),
        ];
        // 验证规则
        $rules  = [
            'oldPassword'  => ['required', '6,32',         '旧密码应为 6 个字符及以上'],
            'newPassword1' => ['required', '6,32',         '新密码应为 6 个字符及以上'],
            'newPassword2' => ['same',     post('newPassword2'), '重复密码与新密码不一致'],
        ];
        // 验证
        $validate = new Validator($data, $rules, true);
        // 验证结果
        $result = $validate->check();
        if (!$result) {
            return json($validate->error);
        }

        // 实例化用户模型
        $user_id = session('user_id');
        $userModel = model('user');
        $user = $userModel->find($user_id);

        // dd(password_hash($data['oldPassword'], PASSWORD_DEFAULT));
        
        // 检查旧密码
        if (!password_verify($data['oldPassword'], $user->password)) {
            return json('原密码错误');
        }

        try {
            $userModel->resetPassword($user_id, $data['newPassword1']);
            return json('修改密码成功', 'success');
        } catch (\Throwable $th) {
            return json('修改密码失败!');
        }
    }
}